package com.ty.dao.impl;

import com.ty.dao.BaseAdminDao;
import com.ty.util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

/**
 * @author 田野
 */
public class BaseAdminDaoImpl implements BaseAdminDao {

    private static final String DML_UPDATE_LOGIN_MSG = " update eadmin set logintime= ?, loginip=? where username=? ";
    /*private static final String DQL_LOGIN = " select * from eadmin where username=? and password=? ";*/
    private static final String DQL_LOGIN = " select id from eadmin where username=? and password=? ";

    /**
     * 根据用户名记录登录时间和登录IP
     *
     * @param userName
     * @param date
     * @param ip
     */
    @Override
    public void updateLoginMsg(String userName, Date date, String ip) {
        // 1、获取连接
        Connection connection = DruidUtil.getConnection();
        // 2、预编译SQL语句
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(DML_UPDATE_LOGIN_MSG);
            // 3、填充参数
            preparedStatement.setDate(1, new java.sql.Date(date.getTime()));
            preparedStatement.setString(2, ip);
            preparedStatement.setString(3, userName);
            // 4、执行SQL语句
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 5、释放资源
            DruidUtil.close(connection, preparedStatement, null);
        }
    }

    /**
     * 管理员根据用户名和密码进行登录验证
     *
     * @param userName
     * @param password
     * @return true 表示登录成功 false 表示登录失败
     */
    @Override
    public boolean login(String userName, String password) {
        // 1、获取连接
        Connection connection = DruidUtil.getConnection();
        // 2、预编译SQL语句
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            preparedStatement = connection.prepareStatement(DQL_LOGIN);
            // 3、填充参数
            preparedStatement.setString(1, userName);
            preparedStatement.setString(2, password);
            // 4、执行SQL语句并返回结果
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                return true;
            } else {
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 5、释放资源
            DruidUtil.close(connection, preparedStatement, resultSet);
        }

        return false;
    }
}
